<?php

namespace App\Trip\Orders\BookOrders\Train\SelectedSeats;

use App\Models\Train\TrainOrderPassengers\TrainOrderPassenger;
use JetBrains\PhpStorm\ArrayShape;

class ParseOrderSelectedSeats
{
    use TraitParseSelectedSeats;

    private array $selected_seats;
    private int   $seat_type;

    /**
     * 多选是当前 selected_seats 的数组
     *
     */
    public function __construct(array $selected_seats)
    {
        $this->selected_seats = $selected_seats;
        $this->seat_type      = collect($this->selected_seats)->value('seat_type') ?: 0;
    }

    #[ArrayShape([
        'unmatched_seats'    => [MatchSeatInfo::class],
        'matched_passengers' => [TrainOrderPassenger::class],
    ])]
    public function matchPassengers($passengers): array
    {
        $matched = [];
        /**
         * @var $passenger TrainOrderPassenger
         * @var $type_seat MatchSeatInfo
         */

        /**
         * 初始化~~ matchSeatInfo
         */
        $selected_seats = $this->getSelectedSeats();
        foreach ($selected_seats as $key => $selected_seat) {
            $selected_seats[$key]['match_seat'] = new MatchSeatInfo($selected_seat);
        }

        foreach ($passengers as $passenger) {
            /**
             * 如果有匹配结果 跳过
             */
            if (isset($matched[$passenger->subPassengerId()])) {
                continue;
            }
            $ticket_seat = $passenger->getTicketSeat();
            if (!$ticket_seat) {
                // 此处应该抛出异常  未出票
                continue;
            }

            foreach ($selected_seats as $selected_seat) {
                $type_seat = $selected_seat['match_seat'];
                if (!$type_seat->match($passenger)) {
                    continue;
                }
                $matched = array_merge($matched, $type_seat->getMatchedPool());
                break;
            }
        }

        $unmatched_seats = [];
        foreach ($selected_seats as $selected_seat) {
            $type_seat = $selected_seat['match_seat'];
            if ($type_seat->getCurrentCount() > 0) {
                $unmatched_seats[] = $type_seat;
            }
        }


        return [
            'unmatched_seats'    => $unmatched_seats,
            'matched_passengers' => $matched,
        ];
    }

    public function getSelectedSeats(): array
    {
        return $this->selected_seats;
    }

}